﻿Namespace Commanding
    Public Class FillCollectionCommand
        Inherits BackgroundCommand

        Private _Collection As IList = Nothing

        Public Shared ReadOnly ClearBeforeFillProperty As DependencyProperty = DependencyProperty.Register("ClearBeforeFill", GetType(Boolean), GetType(FillCollectionCommand))
        Public Property ClearBeforeFill As Boolean
            Get
                Return GetValue(ClearBeforeFillProperty)
            End Get
            Set(ByVal value As Boolean)
                SetValue(ClearBeforeFillProperty, value)
            End Set
        End Property


        Public Overrides Function CanExecute(sender As Object, parameter As Object) As Boolean
            Dim result As Boolean = MyBase.CanExecute(sender, parameter)
            If result Then
                result = parameter IsNot Nothing AndAlso TypeOf parameter Is IList
            End If
            Return result
        End Function

        Protected Overrides Sub OnExecuted(sender As Object, e As System.Windows.Input.ExecutedRoutedEventArgs)
            _Collection = e.Parameter
            If ClearBeforeFill Then
                _Collection.Clear()
            End If
            MyBase.OnExecuted(sender, e)
        End Sub

        Protected Overrides Sub OnProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs)
            MyBase.OnProgressChanged(sender, e)
            _Collection.Add(e.UserState)
        End Sub

        Protected Overrides Sub OnCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)
            MyBase.OnCompleted(sender, e)
            _Collection = Nothing
        End Sub

        Protected Overrides Function CreateInstanceCore() As System.Windows.Freezable
            Return New FillCollectionCommand
        End Function

    End Class
End Namespace